package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishMapper;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author Gareth Cao
 * @date 2022/4/28 16:13
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    //需要操作两张表,进行事务管理
    @Transactional
    public void addByDto(DishDto dishDto) {
        //新增菜品,dishDto封装了dish表所需要的所有数据
        this.save(dishDto);

        //从封装的数据对象中获取口味集合,集合中包含name和value属性
        List<DishFlavor> flavors = dishDto.getFlavors();
        //但是dish_flavor表还需要dish_id值,但是一旦dish表新增之后,id就有值了,可以从dishDto对象中获取;
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        //将口味添加到dish_flavor表中
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id来查询dish表和dish_flavor表,封装到dishDao中
     *
     * @param id
     * @return
     */
    @Override
    public DishDto selectById(Long id) {
        //查询dish表中的数据
        Dish dish = this.getById(id);
        //从dish_flavor表查询数据
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
        //dishDto属性由dish,dishFlavorList组成
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }

    @Override
    @Transactional //事务管理
    public void updateByDishDto(DishDto dishDto) {
        //修改菜品
        this.updateById(dishDto);
        //修改dish_flavor表,根据dish表中id删除相对应的dish_flavor表的dish_id这一组数据
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //将dishDto表中的flavors属性添加到dish_flavor表中
        List<DishFlavor> flavors = dishDto.getFlavors();
        //因为这些集合中的每个dishFlavor缺少dish_id,而dish_id是不为空的
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }
}
